from tools9 import (time_to_minutes,calculate_work_end_time,parse_shift,
                    safe_parse_list,get_allowed_shifts,
                    calculate_work_start_time,calculate_unload_done_time,calculate_arrive_time,
                    double_zero_priority_sort,check_ab_vehicles)
import random



def double_zero_tasks(df,today_tasks, driver_df,vehicle_df,assigned_vehicles, assigned_drivers):
    '''
    筛选双零箔
    '''
    result_df = []
    # 筛选双零箔任务
    double_zero_df = df[df['cargo_type']=="双零箔"].copy()
    count =0
    for _, task in double_zero_df.iterrows():
        result = double_zero_task(task,driver_df,vehicle_df,assigned_vehicles,assigned_drivers)
        if today_tasks['双零箔']['four_point_two']  <= count < (today_tasks['双零箔']['four_point_two'] + today_tasks['双零箔']['ten_point_five']) :
            result['车牌号'] = result['车牌号'] + '/' + vehicle_df[vehicle_df['type'] == '10.5米挂车']['plate_number'].iloc[0]
        if (today_tasks['双零箔']['four_point_two'] + today_tasks['双零箔']['ten_point_five']) <= count < (today_tasks['双零箔']['four_point_two'] + today_tasks['双零箔']['ten_point_five'] + today_tasks['双零箔']['thirteen']):
            random_number = random.randint(0, 3)
            result['车牌号'] = result['车牌号'] + '/' + vehicle_df[vehicle_df['type'] == '13米挂车']['plate_number'].iloc[random_number]

        assigned_vehicles.add(result['车辆ID'])
        assigned_drivers.add(result['司机姓名'])
        result_df.append(result)
        count+=1
    return result_df,assigned_vehicles,assigned_drivers

def double_zero_task(task,driver_df,vehicle_df,assigned_vehicles,assigned_drivers):

    departure_time = task['departure_time']
    task_shift = parse_shift(departure_time)
    # 先安排司机
    selected_driver = assign_driver_for_double_zero(
        task, task_shift, driver_df, assigned_drivers
    )

    selected_vehicle = assign_vehicle_for_double_zero(
        task, task_shift, vehicle_df, assigned_vehicles,selected_driver
    )

    # 计算收车时间
    end_time = "20:00"


    return {
        '发车时间': departure_time,
        '装货时间': task['load_time'],
        '货物类型': '双零箔',
        '车辆ID': selected_vehicle['vehicle_id'],
        '车辆类型': selected_vehicle['type'],
        '车牌号': selected_vehicle['plate_number'],
        '司机ID': selected_driver['driver_id'],
        '司机姓名': selected_driver['driver_name'],
        '司机所属地区': selected_driver['region'],
        '是否接车': task['is_transfer'],
        '收车时间': end_time
    }


def assign_driver_for_double_zero(task, task_shift, driver_df, assigned_drivers):
    '''
    1.长沙
    2. 早晚班
    3. 双零箔次数
    4. 休息时间
    '''
    available_drivers = driver_df[
            (~driver_df['driver_name'].isin(assigned_drivers)) &
            (driver_df['region'] == '长沙')].copy()
    available_drivers['history_shifts'] = available_drivers['last_4days_departure_times'].apply(
        lambda x: [parse_shift(t) for t in safe_parse_list(x) if t is not None]
    )
    available_drivers['allowed_shifts'] = available_drivers['history_shifts'].apply(get_allowed_shifts)
    available_drivers = available_drivers[
        available_drivers['allowed_shifts'].apply(lambda x: task_shift in x if x else False)
    ]
    available_drivers['start_time'] = available_drivers['region'].apply(
        lambda x: calculate_work_start_time(load_time=task['load_time'],
                                            departure_time=task['departure_time'],
                                            region=x,
                                            cargo_type=task['cargo_type'])
    )
    available_drivers['time_priority'] = time_to_minutes(available_drivers['start_time']) - time_to_minutes(
        available_drivers['end_time'])

    available_drivers['count_priority'] = available_drivers.apply(double_zero_priority_sort, axis=1)
    available_drivers['li_shengguo_priority'] = available_drivers['driver_name'].apply(
        lambda x: 0 if x == '李胜果' else 1
    )

    available_drivers = available_drivers.sort_values(
        by=['li_shengguo_priority','time_priority','count_priority','driver_id'],
        ascending=[True, False, True, True]
    )
    return available_drivers.iloc[0]

def assign_vehicle_for_double_zero(task, task_shift, vehicle_df, assigned_vehicles, selected_driver):
    '''

    1. 筛选已经排完的车
    2. 车的地区和人的地区一致
    3.表里面车型一致
    4. ab角
    '''
    available_vehicles = vehicle_df[(~vehicle_df['vehicle_id'].isin(assigned_vehicles))&
                                   (vehicle_df['region'] == '长沙')&
                                   (task['vehicle_type'] == vehicle_df['type'])
                                   ].copy()
    # 出车时间与收车时间间隔大于9小时
    available_vehicles = available_vehicles[
        time_to_minutes(selected_driver['start_time']) - time_to_minutes(available_vehicles['end_time']) < 900]

    # 计算AB角优先级
    available_vehicles['ab_priority'] = available_vehicles['ab_drivers'].apply(
        lambda x: check_ab_vehicles(x, selected_driver['driver_name'])
    )

    # 按AB角优先级排序（A角优先），然后按司机ID排序
    available_vehicles = available_vehicles.sort_values(
        by=['ab_priority', 'vehicle_id'],
        ascending=[False, True]
    )
    selected_vehicle = available_vehicles.iloc[0]

    if selected_vehicle is None:
        print(f"没有可用车辆用于废铝/铝卷任务: {task['departure_time']}")
        return None

    return selected_vehicle








